package com.parp.visuals;

import java.util.ArrayList;
import java.util.List;
import com.utils.TraceLine;
import android.graphics.Canvas;
import android.graphics.Paint;

public class LineVisual implements Visual{
	//Lists of current and old lines
	private final List<TraceLine> lines =  new ArrayList<TraceLine>();
	private final List<TraceLine> oldLines =  new ArrayList<TraceLine>();
	private final Paint linePaint = new Paint();
	//Store coordinates of the last two points touched.
	private float[] lastX = {-1f,-1f};
	private float[] lastY = {-1f,-1f};
	private boolean enable = true;
	
	@Override
	public void enable(boolean enable)
	{
		this.enable = enable;
		synchronized(lines) {
			this.lines.clear();
			this.oldLines.clear();
		}
	}
	
	@Override
	public void motionUpdate(int pointerId, float x, float y, long time, int height) {
		if(enable) {
			if(lastX[pointerId] > -1 && lastY[pointerId] > -1)
			{//Add a new line to the list of lines to be drawn
				lines.add(new TraceLine(x,y,lastX[pointerId],lastY[pointerId]));
			}//Update location of last point touched for next time
			lastX[pointerId] = x;
			lastY[pointerId] = y;
		}
	}

	@Override
	public void drawVisual(int pointerId, Canvas canvas, float x, float y, long time) {
		if(enable) {
			// Draw each line in the list
			for(TraceLine l : lines)
			{
				linePaint.setColor(l.getColor());
				linePaint.setStrokeWidth(l.getThickness());
				canvas.drawLine(l.getStartX(), l.getStartY(), l.getEndX(), l.getEndY(), linePaint);
				if(l.fade())
				{//If a line has faded to invisibility, mark it for removal
					oldLines.add(l);
				}
			}//Clear any lines that no longer need to be drawn
			if(oldLines.size() > 0)
			{
				lines.removeAll(oldLines);
				oldLines.clear();
			}
		}
	}
	//On finger up, clear last touched points
	@Override
	public void up()
	{
		if(enable) {
			for(int i = 0; i<lastX.length; i++)
			{
				lastX[i] = -1;
				lastY[i] = -1;
			}
		}
	}
}
